package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.cart.service.CartAsyncService;
import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.model.cart.CartInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Author LEO
 * @Date 2021年12月17日 14:03
 */
@Service
public class CartAsyncServiceImpl implements CartAsyncService {
    @Autowired
    private CartInfoMapper cartInfoMapper;

    /**
     * 新增
     * @param cartInfo
     */
    @Override
    @Async    //实现异步
    public void saveCartInfo(CartInfo cartInfo) {
        // int i=1/0;
        cartInfoMapper.insert(cartInfo);

    }

    /**
     * 更新
     * @param cartInfo
     */
    @Override
    @Async    //实现异步
    public void updateCartInfo(CartInfo cartInfo) {
        //代码有问题

       // cartInfoMapper.updateById(cartInfo);
        // update cart_info set sku_num = ? where sku_id=? and user_id = ?
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id",cartInfo.getSkuId());
        queryWrapper.eq("user_id",cartInfo.getUserId());
        cartInfoMapper.update(cartInfo,queryWrapper);
    }

    // 异步删除
    @Override
    @Async    //实现异步
    public void deleteCartInfo(CartInfo cartInfo) {
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cartInfo.getUserId());
        cartInfoMapper.delete(queryWrapper);
    }


    @Override
    @Async    //实现异步
    public void deleteCartInfoByUserId(String userId) {
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        cartInfoMapper.delete(queryWrapper);
    }

    // 选中状态变更
    @Override
    @Async    //实现异步
    public void checkCart(String userId, Integer isChecked, Long skuId) {
        // update cart_info set is_checked = ? where userId=? and skuId=?
        CartInfo cartInfo = new CartInfo();
        cartInfo.setIsChecked(isChecked);
        UpdateWrapper<CartInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",userId);
        updateWrapper.eq("sku_id",skuId);
//        updateWrapper.set("is_checked",isChecked);
        cartInfoMapper.update(cartInfo,updateWrapper);

    }

    @Override
    @Async    //实现异步
    public void deleteCartInfo(String userId, Long skuId) {
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("sku_id",skuId);
        cartInfoMapper.delete(queryWrapper);
    }
}
